// 图片压缩
export default function commonZipPic(file, scale) {
  return new Promise((resolve, reject) => {
    const image = new Image()
    let resultBlob = ''
    image.src = URL.createObjectURL(file)
    image.onload = () => {
      // 调用方法获取blob格式，方法写在下边
      resultBlob = compressUpload(image, file, scale)
      const fs = new File([resultBlob], file.name, {
        type: file.type
      })
      resolve(fs)
    }
    image.onerror = () => {
      reject()
    }
  })
}

/* 图片压缩方法-canvas压缩 */
// scale 图片width压缩比例
function compressUpload(image, file, scale) {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const { width } = image
  const { height } = image
  const targetWidth = Math.round(width * Number(scale))
  const targetHeight = Math.round(height * Number(scale))
  canvas.width = targetWidth
  canvas.height = targetHeight
  ctx.clearRect(0, 0, targetWidth, targetHeight)
  // 重绘压缩
  ctx.drawImage(image, 0, 0, targetWidth, targetHeight)
  const compressData = canvas.toDataURL(file.type || 'image/jpeg')
  // base64转Blob
  const blobImg = dataURItoBlob(compressData)
  return blobImg
}
/* base64转Blob对象 */
function dataURItoBlob(data) {
  let byteString
  if (data.split(',')[0].indexOf('base64') >= 0) {
    byteString = window.atob(data.split(',')[1])
  } else {
    byteString = unescape(data.split(',')[1])
  }
  const mimeString = data
    .split(',')[0]
    .split(':')[1]
    .split(';')[0]
  const ia = new Uint8Array(byteString.length)
  for (let i = 0; i < byteString.length; i += 1) {
    ia[i] = byteString.charCodeAt(i)
  }
  return new Blob([ia], { type: mimeString })
}
